package com.anbang.app.ui.animation.views

import android.content.Context
import android.util.AttributeSet
import androidx.core.widget.NestedScrollView


/**
 * @Description: 动画相关ScrollView
 * @Author: AnBang
 * @Date: 2019/1/17 22:00
 */
class AnimScrollView(context: Context, attrs: AttributeSet?) : NestedScrollView(context, attrs) {

    private lateinit var contentView: DiscrollViewContent

    /**
     * xml 文件读取完成
     */
    override fun onFinishInflate() {
        super.onFinishInflate()
        if (childCount > 0) {
            val view = getChildAt(0)
            if (view is DiscrollViewContent) {
                contentView = getChildAt(0) as DiscrollViewContent
            }
        }
    }

    /**
     * 布局大小改变调用 , 初始化会调用一次
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        if (childCount > 0) {
            val view = getChildAt(0)
            //将子布局高度设置为 ScrollView 高度
            view.layoutParams.height = height
        }
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)
        //监听滑动----接口---->控制DiscrollViewContent的属性
        // 遍历MyLinearLayout里面所有子控件(MyViewGroup)
        for (i in 0 until contentView.childCount) {
            val childView = contentView.getChildAt(i)
            if (childView is DiscrollvableInterface) {
                val childViewInterface = childView as DiscrollvableInterface
                //1.child离scrollview顶部的高度 a
                val discrollvableTop = childView.top
                val discrollvableHeight = childView.height

                //2.得到scrollview滑出去的高度  b  就是int t,
                //3.得到child离屏幕顶部的高度  c
                val discrollvableAbsoluteTop = discrollvableTop - t
                //什么时候执行动画？当child滑进屏幕的时候
                if (discrollvableAbsoluteTop <= height) {
                    val visibleGap = height - discrollvableAbsoluteTop
                    //确保ratio是在0~1，超过了1 也设置为1
                    childViewInterface.onDiscrollve(clamp((visibleGap / discrollvableHeight.toFloat()), 1f, 0f))
                } else {//否则，就恢复到原来的位置
                    childViewInterface.onResetDiscrollve()
                }
            }
        }
    }

    private fun clamp(value: Float, max: Float, min: Float): Float {
        return Math.max(Math.min(value, max), min)
    }
}